package com.yuanlang.web.controller;

import com.alibaba.fastjson.JSON;
import com.yuanlang.common.ResultMap;
import com.yuanlang.common.util.AccessToken;
import com.yuanlang.common.util.SystemMsgCode;
import com.yuanlang.facade.model.system.TsUser;
import com.yuanlang.services.redis.RedisClientTemplate;
import com.yuanlang.services.system.TsUserRoleService;
import com.yuanlang.services.system.TsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@CrossOrigin(origins = "*", maxAge = 3600) // 设置跨域访问
@RequestMapping(value = "login")
public class LoginController {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    TsUserService tsUserService;
    @Autowired
    HttpServletRequest request;
    @Value("${sessionTimeOut}")
    private int sessionTimeOut;
    @Autowired
    private RedisClientTemplate redisClientTemplate;
    @Autowired
    private TsUserRoleService tsUserRoleService;



    /**
     * @return {code:success;msg;msgContent:data}
     * @throws {如果有异常说明请填写}
     * @methodname doLogin
     * @Description {登录方法}
     * @author 黄学乾
     * @create 2018/3/23/023 19:32
     */
    @RequestMapping(value = "/doLogin",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json")
    @ResponseBody
    public ResultMap doLogin(String username, String password) { // HttpServletRequest request
        ResultMap result = new ResultMap();
        try {
            List<TsUser> tsUserList = tsUserService.findTsUser(username);
            String sessionId = request.getSession().getId();
            if (tsUserList != null && tsUserList.size() > 0) {
                // 存在账号
                for (TsUser tsUser : tsUserList) {
                    if (tsUser.getIslock() == 0) {
                        if (password.equals(tsUser.getPassword())) {
                            AccessToken accessToken = new AccessToken();
                            // 判断是否管理员
                            Boolean isAdmin = tsUserRoleService.isAdmin(tsUser.getUserId());
                            accessToken.setAccess_token(sessionId);
                            tsUser.setAdmin(isAdmin);
                            result.setCode(SystemMsgCode.SYS_SUCCEED.getResultCode());
                            result.setMsg(SystemMsgCode.SYS_SUCCEED.getResultMessage());
                            result.setData(accessToken);
                            try {
                                redisClientTemplate.set(sessionId, JSON.toJSONString(tsUser), "NX", "EX", sessionTimeOut);
                            } catch (Exception e) {
                                e.printStackTrace();
                                result.setCode(SystemMsgCode.SYS_REDIS_FAILED.getResultCode());
                                result.setMsg(SystemMsgCode.SYS_REDIS_FAILED.getResultMessage());
                                logger.error("登录错误："+e.getLocalizedMessage());
                            }
                        } else {
                            result.setCode(SystemMsgCode.LOGIN_FAILED_ERR_PWD.getResultCode());
                            result.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.LOGIN_FAILED_ERR_PWD.getResultCode()));
                        }
                    } else {
                        result.setCode(SystemMsgCode.LOGIN_ACCT_IS_LOCKED.getResultCode());
                        result.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.LOGIN_ACCT_IS_LOCKED.getResultCode()));
                    }
                }
            } else {
                result.setCode(SystemMsgCode.LOGIN_FAILED_ERR_PWD.getResultCode());
                // 账号不存在
                result.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.LOGIN_FAILED_ERR_PWD.getResultCode()));
            }
        } catch (Exception e) {
            result.setCode(SystemMsgCode.SYS_EXCEPTION.getResultCode());
            // 系统异常
            result.setMsg(SystemMsgCode.getSystemMsg(SystemMsgCode.SYS_EXCEPTION.getResultCode())+":"+e.getLocalizedMessage());
        }
        return result;
    }


    /**
     * @throws {如果有异常说明请填写}
     * @methodname 退出登录
     * @Description 退出登录，记录日志并销毁所有会话
     * @author 黄学乾
     * @create 2018/3/22/022 23:18
     */
    @RequestMapping("/exitLogin")
    @ResponseBody
    public ResultMap exitLogin(HttpServletRequest request) {
        String access_token = request.getParameter("access_token");
        // 清除redis缓存，记录退出日志 ;
        redisClientTemplate.del(access_token);
        ResultMap result = new ResultMap();
        result.setCode(0);
        result.setMsg("退出成功");
        return result ;
    }



}
